package cn.swu.ws.webCounter;

import cn.swu.ws.dao.MysqlDbDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@WebServlet("/findCounter")
public class findCounter extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hitCount = 0;
        Connection connection;
        Statement statement;
        ResultSet resultSet;
        String sql = "select id,counter from WebPageCounter;";
        try {
            connection = MysqlDbDao.login_database();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                hitCount = resultSet.getInt("counter");
                System.out.println(hitCount);;
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        String json_tem = "{\n" +
                "\t\"state\": 200,\n" +
                "\t\"counter\":%d,\n" +
                "\t\"totalCounter\":%d,\n" +
                "\t\"data\": null\n" +
                "}";
        String re = String.format(json_tem, WebCounter.counter,hitCount);
        Writer writer = resp.getWriter();
        writer.write(re);
    }
}
